#!/usr/bin/env python3
"""
Aggressive table cleanup for LaTeX files
"""

import re
import os
from pathlib import Path

def aggressive_table_cleanup(content):
    """Remove all malformed table structures"""
    
    # Remove all table environments that seem problematic
    # This is an aggressive approach - we'll remove tables entirely for now
    content = re.sub(
        r'\\begin\{table\}.*?\\end\{table\}',
        '',
        content,
        flags=re.MULTILINE | re.DOTALL
    )
    
    # Remove stray \\hline commands
    content = re.sub(r'\\hline\s*', '', content)
    
    # Remove stray tabular environments
    content = re.sub(
        r'\\begin\{tabular\}.*?\\end\{tabular\}',
        '',
        content,
        flags=re.MULTILINE | re.DOTALL
    )
    
    # Remove any remaining table markup
    content = re.sub(r'\\centering\s*', '', content)
    
    # Clean up multiple empty lines
    content = re.sub(r'\n\s*\n\s*\n+', '\n\n', content)
    
    return content

def fix_file(file_path):
    """Aggressively fix a single file"""
    print(f"Aggressively fixing {file_path}")
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        fixed_content = aggressive_table_cleanup(content)
        
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(fixed_content)
            
    except Exception as e:
        print(f"Error fixing {file_path}: {e}")

def main():
    """Fix files with table issues"""
    problematic_files = [
        "/home/linden/claude/packages/ccwork/claude-code-development-book/chapters/appendix-a-templates.tex",
        "/home/linden/claude/packages/ccwork/claude-code-development-book/chapters/17-authentication-security.tex", 
        "/home/linden/claude/packages/ccwork/claude-code-development-book/chapters/05-code-debugging-builds.tex",
        "/home/linden/claude/packages/ccwork/claude-code-development-book/chapters/appendix-b-patterns.tex",
        "/home/linden/claude/packages/ccwork/claude-code-development-book/chapters/12-documentation-wiki.tex",
        "/home/linden/claude/packages/ccwork/claude-code-development-book/chapters/09-data-processing-analysis.tex"
    ]
    
    for file_path in problematic_files:
        if os.path.exists(file_path):
            fix_file(file_path)
    
    print("Aggressive table cleanup complete!")

if __name__ == "__main__":
    main()